package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.FunRolePageRequest;
import com.jiyinit.web.core.business.dto.FunRoleRequest;
import com.jiyinit.web.core.business.dto.RolePageRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreRoleEntity;
import com.jiyinit.web.core.business.entity.TabCoreRoleResourceEntity;
import com.jiyinit.web.core.business.entity.TabFunRoleEntity;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.enums.ResourceTypeEnum;
import com.jiyinit.web.core.business.service.*;
import com.jiyinit.web.core.business.vo.FunctionRoleVo;
import com.jiyinit.web.core.business.vo.FunctionVo;
import com.jiyinit.web.core.business.vo.RoleResourceVo;
import com.jiyinit.web.core.business.vo.UserInfoVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author changly
 * @version 1.0
 * @date 2017/12/21 17:34
 * @since 1.0
 */
@Controller
@RequestMapping("/funRole")
public class FunRoleController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FunRoleController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "function.funRoleServiceImpl")
    private FunRoleServiceImpl funRoleServiceImpl;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgServiceImpl;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "core.funRoleUserService")
    private FunRoleUserServiceImpl funRoleUserService;




    /**
     * 列表页面
     * @author changly
     * @create 2017/12/21 17:37
     * @param
     * @return
     */
    @RequestMapping("/list")
    public String roleList() {
        return "/function/role/funRoleList";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "/function/role/add";
    }

    @ResponseBody
    @RequestMapping("add")
    public ResponseEntity<ResponseDto> add(FunRoleRequest request){
        int num = funRoleServiceImpl.add(request);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""),HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail(""),HttpStatus.OK);
    }


    @RequestMapping("/toUpdate")
    public String toUpdate(Integer funRoleId,Model model) {
        TabFunRoleEntity entity = funRoleServiceImpl.findById(funRoleId);
        model.addAttribute("funRole",entity);
        return "/function/role/update";
    }

    @ResponseBody
    @RequestMapping("/update")
    public ResponseEntity<ResponseDto> update(FunRoleRequest request){
        int num = funRoleServiceImpl.update(request);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""),HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail(""),HttpStatus.OK);
    }


    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/findByPage")
    public PagingResult<FunctionRoleVo> findByPage(HttpServletRequest request,FunRolePageRequest funRolePageRequest){
        Integer orgId = UserUtil.getCurrentUser().getOrgId();
        PagingResult<FunctionRoleVo> result = funRoleServiceImpl.findByPage(orgId, funRolePageRequest);
        return  result;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/anon/funDeleteCheck")
    public ResponseEntity<ResponseDto> funDeleteCheck(Integer[] funRoleIds){
        //是不是默认模板
         List<TabFunRoleEntity> list = funRoleServiceImpl.findByIds(funRoleIds);
        for (TabFunRoleEntity entity : list){
           if(CommonEnum.FunRoleType.DEFAULT.getCode().intValue() == entity.getFunRoleType().intValue()){
               return new ResponseEntity<>(ResponseDto.responseFail("默认角色不允许删除"),HttpStatus.OK);
           }
        }
        return  new ResponseEntity<>(ResponseDto.responseOK(""),HttpStatus.OK);
        //查询存在用户不允许删除
    }
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public ResponseEntity<ResponseDto> delete(Integer[] funRoleIds){
        int num  = funRoleServiceImpl.delete(funRoleIds);
        if(num > 0)
            return new ResponseEntity<>( ResponseDto.responseOK(""),HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail(""),HttpStatus.OK);
    }

    @RequestMapping("toRoleTreeUpdate")
    public String toTreeUpdate(Integer funRoleId,Model model){
        Integer orgId = UserUtil.getCurrentUser().getOrgId();
        Integer parentId = orgServiceImpl.getTopParentOrgId(orgId);
        model.addAttribute("orgId",parentId);
        model.addAttribute("funRoleId",funRoleId);
        return "function/role/treeUpdate";
    }

    @ResponseBody
    @RequestMapping("anon/findRoleFunction")
    public ResponseEntity<ResponseDto> treeUpdate(Integer orgId,Integer funRoleId){
        List<FunctionVo> list = funRoleServiceImpl.findOrgFunction(orgId,funRoleId);
        List items = new ArrayList<>();
        for(FunctionVo fun : list){
            Map<String, Object> map = new HashMap<>();
            map.put("id", fun.getFunId());
            map.put("pId", fun.getParentId());
            map.put("name", fun.getFunName());
            if(fun.getNum() != null && fun.getNum() >0){
                map.put("open", true);
            } else {
                map.put("open", false);
            }
            if(!Check.isNullObj(fun.getId())){
                map.put("checked", true);
            }
            items.add(map);
        }
        return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
    }


    @ResponseBody
    @RequestMapping("updateTree")
    public ResponseEntity<ResponseDto> update(Integer orgId,Integer[] funIds,Integer funRoleId){
        if(funIds == null){
            return new ResponseEntity<>(ResponseDto.responseFail("功能ID不能为空！"),HttpStatus.OK);
        }
        int num = funRoleServiceImpl.updateRoleFunction(orgId, funRoleId,funIds);
        if(num >0)
            return new ResponseEntity<>(ResponseDto.responseOK(""),HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("失败！"),HttpStatus.OK);
    }

    @RequestMapping("toChooseUser")
    public String toChooseUser(Integer funRoleId,Model model){
        Integer orgId = UserUtil.getCurrentUser().getOrgId();
        Integer parentId = orgServiceImpl.getTopParentOrgId(orgId);
        model.addAttribute("orgId",parentId);
        model.addAttribute("funRoleId",funRoleId);
        return "function/role/chooseUser";
    }

    @ResponseBody
    @RequestMapping("anon/findUsersByfunRoleId")
    public  ResponseEntity<ResponseDto> findUsersByfunRoleId(Integer orgId,Integer funRoleId){
        List items = new ArrayList<>();
        //查询当前机构下的所有部门
        List<TabCoreOrgEntity> orgList = orgServiceImpl.getChildOrgById(orgId);
        //查询用户与角色用户的关系
        List<UserInfoVo> userList = userService.findUsersByfunRoleId(orgList,funRoleId);

        for (TabCoreOrgEntity org: orgList){
            Map<String, Object> map = new HashMap<>();
            map.put("id","o"+org.getOrgId());
            map.put("pId", "o"+org.getParentId());
            map.put("name", org.getOrgName());
            if(org.getOrgLevel() < 1){
                map.put("open", true);
            } else {
                map.put("open", false);
            }
                map.put("checked", false);

            items.add(map);
        }
        for (UserInfoVo user: userList){
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getUserId());
            map.put("pId","o"+user.getOrgId());
            map.put("name", user.getUserName());
            map.put("open", false);

            if(!Check.isNullObj(user.getId())) {
                map.put("checked", true);
            }

            items.add(map);
        }

        return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
    }

    @ResponseBody
    @RequestMapping("chooseUser")
    public ResponseEntity<ResponseDto> updateUsers(Integer orgId,String[] userIds,Integer funRoleId){
        List<Integer> ids = new ArrayList<>();
        if(userIds == null){
            return new ResponseEntity<>(ResponseDto.responseFail("用户ID不能为空！"),HttpStatus.OK);
        }
        for (int i = 0; i <= userIds.length-1; i++) {
            if(userIds[i].startsWith("o")) continue;
            ids.add(new Integer(userIds[i]));
        }
        int num = funRoleUserService.updateRoleFunction(orgId, funRoleId,ids);
        if(num >0)
            return new ResponseEntity<>(ResponseDto.responseOK(""),HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("失败！"),HttpStatus.OK);
    }

}
